<!DOCTYPE html>
<html lang="zh">

<head>
  <th:block th:include="include :: header('历史数据查询')" />
  <th:block th:include="include :: layout-latest-css" />
  <th:block th:include="include :: ztree-css" />
  <style>
    #bootstrap-table tbody tr {
      position: relative;
    }

    #noneBox {
      position: absolute;
      width: 333px;
      height: 200px;
      top: 36px;
      left: 30%;
      /* display: none; */
      background-color: #e8e8e8;
      z-index: 100;
      border-radius: 10px;
    }

    #noneBox::after {
      content: "";
      position: absolute;
      top: -20px;
      left: 50%;
      transform: translate(-50%);
      left: 50%;
      border-top: 10px solid transparent;
      border-left: 10px solid transparent;
      border-right: 10px solid transparent;
      border-bottom: 10px solid black;
    }

    .fixed-table-body {
      border: 1px solid #ccc;
    }

    .tip_text {
      position: absolute;
      top: 36px;
      left: 38%;
      width: max-content;
      font-size: 12px;
      font-weight: 400;
      word-break: break-word;
      padding: 6px 8px;
      border-radius: 4px;
      z-index: 99999;
      background: #fff;
      border: 1px solid #303133;
      color: #303133;
    }

    .tip_text::after {
      content: "";
      position: absolute;
      top: -15px;
      left: 50%;
      transform: translate(-50%);
      left: 50%;
      border-top: 7px solid transparent;
      border-left: 7px solid transparent;
      border-right: 7px solid transparent;
      border-bottom: 7px solid black;
    }

    .fixed-table-container {
      height: 500px;
    }

    .table-striped table>thead>tr>th,
    .table-striped table>tbody>tr>th,
    .table-striped table>tfoot>tr>th,
    .table-striped table>thead>tr>td,
    .table-striped table>tbody>tr>td,
    .table-striped table>tfoot>tr>td { 
      border: 1px solid #e7eaec;
    }
  </style>
</head>

<body class="gray-bg">
  <!-- <div class="ui-layout-west">
    <div class="box box-main">
      <div class="box-header">
        <div class="box-title"><i class="fa icon-grid"></i>实时监测</div>
        <div class="box-tools pull-right">
          <a type="button" class="btn btn-box-tool" href="#" onclick="dept()" title="管理部门"><i
              class="fa fa-edit"></i></a>
          <button type="button" class="btn btn-box-tool" id="btnExpand" title="展开" style="display: none">
            <i class="fa fa-chevron-up"></i>
          </button>
          <button type="button" class="btn btn-box-tool" id="btnCollapse" title="折叠">
            <i class="fa fa-chevron-down"></i>
          </button>
          <button type="button" class="btn btn-box-tool" id="btnRefresh" title="刷新部门">
            <i class="fa fa-refresh"></i>
          </button>
        </div>
      </div>
      <div class="ui-layout-content">
        <div id="tree" class="ztree"></div>
      </div>
    </div>
  </div> -->

  <div class="ui-layout-center">
    <div class="container-div">
      <div class="row">
        <div class="col-sm-12 search-collapse">
          <form id="user-form">
            <!-- <input type="hidden" name="pageSize" value="10000" />
          <input type="hidden" id="workspaceCategoryId" name="workspaceCategoryId" /> -->
            <div class="select-list">
              <ul>
                <li style="display: flex;">
                  <label style="margin-right: 10px;width: 80px;">请选择机构:</label>
                  <select name="azqyid" id="dev_azdw1_select1" class="first form-control azdw-select1" data-index="1"
                    style="width: 95px;">
                  </select>
                </li>
                <li>
                  <select name="ejdw_id" id="dev_azdw2_select1" class="second form-control azdw-select1" data-index="2"
                    style="width: 95px;"></select>
                </li>
                <li>
                  <select name="dw_3_id" id="dev_azdw3_select1" class="third form-control azdw-select1" data-index="3"
                    style="width: 95px;"></select>
                </li>
                <li style="display: flex;">
                  <label style="width: 80px;">监测点名称:</label>
                  <input type="text" style="width: 120px;" name="pointName" placeholder="请输入监测点名称">
                </li>
                <li>
                  开始时间：
                  <input type="date" name="reostartTime" class="layui-input startTime" />
                </li>
                <li>
                  结束时间：
                  <input type="date" name="reoendTime" class="layui-input startTime" />
                </li>
                <li>
                  <a class="btn btn-primary btn-rounded btn-sm" onclick="$.table.search()"><i
                      class="fa fa-search"></i>&nbsp;搜索</a>
                  <a class="btn btn-warning btn-rounded btn-sm" onclick="$.form.reset()"><i
                      class="fa fa-refresh"></i>&nbsp;重置</a>
                </li>
              </ul>
            </div>
          </form>
        </div>
        <!-- <form id="user-form">
        <div class="col-sm-12 search-collapse">
          <form id="user-form">
            <input type="hidden" name="pageSize" value="10000" />
            <input type="hidden" id="workspaceCategoryId" name="workspaceCategoryId" value="15" />
            <div class="select-list">
              <ul>
                <li>
                  <label style="margin-right: 10px;width: 80px;">请选择场景:</label>
                  <select id="first" style="max-width:120px" class="first form-control m-b">
                    <option value="">请选择</option>
                  </select>
                </li>
                <li>
                  <a class="btn btn-primary btn-rounded btn-sm" onclick="$.table.search()"><i
                      class="fa fa-search"></i>&nbsp;搜索</a>
                  <a class="btn btn-warning btn-rounded btn-sm" id="reset"><i class="fa fa-refresh"></i>&nbsp;重置</a>
                </li>
              </ul>
            </div>
          </form>

        </div>
        <div class="col-sm-12 select-table table-striped">
          <table id="bootstrap-table"></table>
        </div>
      </div>
    </div>
  </div>

  <div class="ui-layout-center">
    <div class="container-div">
      <div class="row">
        <form id="user-form">
          <input type="hidden" name="pageSize" value="10000" />
          <input type="hidden" id="workspaceCategoryId" name="workspaceCategoryId" value="1" />
        </form> -->
        <div class="col-sm-12 select-table table-striped">
          <table id="bootstrap-table"></table>
        </div>
      </div>
    </div>
    <!-- 图表 -->
  </div>

  <th:block th:include="include :: footer" />
  <th:block th:include="include :: layout-latest-js" />
  <th:block th:include="include :: ztree-js" />
  <script src="/js/layui.js" th:src="@{/js/layui.js}"></script>
  <script src="/js/echarts.min.js" th:href="@{/js/echart.min.js}"></script>
  <script src="/js/echarts.js" th:src="@{/js/echarts.js}"></script>
  <script th:inline="javascript">
    // var editFlag = [[${@permission.hasPermi('youtianNew:basicsMangement:edit')}]];
    // var removeFlag = [[${@permission.hasPermi('system:user:remove')}]];
    // var resetPwdFlag = [[${@permission.hasPermi('system:user:resetPwd')}]];
    var treeClick = null;
    $(function () {
      var panehHidden = false;
      if ($(this).width() < 769) {
        panehHidden = true;
      }
      $("body").layout({ initClosed: panehHidden, west__size: 185 });
      // 回到顶部绑定
      if ($.fn.toTop !== undefined) {
        var opt = {
          win: $(".ui-layout-center"),
          doc: $(".ui-layout-center"),
        };
        $("#scroll-up").toTop(opt);
      }
      queryUserList();
      // queryDeptTree();
      // initfirst()
      initAZDWselect1()
      $('.azdw-select1').change(function (e) {
        var getSelectIndex = $(this).attr("data-index") || 1;
        var maxSelectIndex = 6;
        var nextSelectIndex = Number(getSelectIndex) + 1;
        let startIndex = getSelectIndex;
        while (startIndex < maxSelectIndex) {
          startIndex++;
          $(`#dev_azdw${startIndex}_select1`).val("").text("请选择")
          $('#equipmentId').val($(this).val())
        }
        // 获取下一级select 下拉框的数据，只有存在下一级的时候，在需要调用设置 option 方法
        if (nextSelectIndex < maxSelectIndex) {
          initAZDWselect1(nextSelectIndex);
        }
        // 调用根据条件筛选监测点
        queryPointSelect1();
      })
    });

    function queryUserList() {
      var options = {
        url: "/youtian/workspace-category/reogetPointList",
        method: "get",
        // showSearch: false,
        onClickRow: onClickRow,
        autoSort: true,
        initSort: {
          field: "sceneName",
          type: "desc",
        },
        pagination: false,
        sortable: false, // 不使用排序
        pageSize: 10000,
        height: "600px",
        onLoadSuccess: function (data) {
          // 渲染完数据之后执行。
          $(".select-table .table-bordered").rowspan(0); //合并第一列中相同的行
        },
        columns: [
          {
            field: "sceneName",
            title: "场景名称",
            unresize: true,
            align: "center",
          },
          {
            field: "pointName",
            title: "监测点名称",
            align: "center",
          },
          {
            field: "deptName",
            title: "所属单位",
            align: "center",
            formatter: function (value, row, index) {
              return deptName = row.bmName + '-' + row.zyqName + '-' + row.dw_3_name
            }
          },
          {
            field: "upperLimit",
            title: "上限值",
            width: 120,
            align: "center",
          },
          {
            field: "lowerLimit",
            title: "下限值",
            width: 120,
            align: "center",
          },

          {
            field: "dataState",
            title: "报警状态",
            align: "center",
          },
          {
            field: "value",
            title: "采集数据",
            align: "center",
          },
          {
            field: "createTime",
            title: "时间",
            align: "center",
          },
        ],
      };
      $.table.init(options);
    }

    // function nowDate() {
    //   let date = new Date();
    //   //对获取的时间进行格式处理
    //   //获取年份 并拼接 -
    //   // var Y = date.getFullYear() + "-";
    //   var YY = date.getFullYear();
    //   //获取月份，如果不超过10就在前面拼接上0，这样看着比较美观统一
    //   // var M = date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) + "-" : date.getMonth() + 1 + "-";
    //   var MM = fillZero(date.getMonth() + 1);
    //   //获取天数
    //   // var D = date.getDate() < 10 ? "0" + date.getDate() + " " : date.getDate() + " ";
    //   var DD = fillZero(date.getDate() );
    //   //获取小时
    //   // var h = date.getHours() < 10 ? "0" + date.getHours() + ":" : date.getHours() + ":";
    //   var hh = fillZero( date.getHours() );
    //   //获取分钟数
    //   // var m = date.getMinutes() < 10  ? "0" + date.getMinutes() + ":" : date.getMinutes() + ":";
    //   var mm = fillZero( date.getMinutes() );
    //   //获取秒速
    //   // var s = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
    //   var ss = fillZero( date.getSeconds() );

    //   // return Y + M + D + h + m + s;
    //   return `${YY}-${MM}-${DD} ${hh}:${mm}:${ss}`;
    // }

    // 点击表格显示图表
    // 定时器
    var setTimeData = "";
    let list = {};
    $('#bootstrap-table1').mouseleave(function () {
      clearInterval(setTimeData)
      $("#noneBox").remove()
    })
    function onClickRow(row, el) {
      var currentTime1 = new Date().setDate(new Date().getDate())
      var currentTime2 = new Date().setHours(new Date().getHours() - 1)
      var startTime = new Date(currentTime1).toLocaleString().replace(/\//g, '-')
      var endTime = new Date(currentTime2).toLocaleString().replace(/\//g, '-')
      console.log(startTime, endTime, '时间');


      clearInterval(setTimeData);
      let echartDom = el.children("#noneBox");
      console.log(echartDom[0], "echartDom");
      if (echartDom[0]) {
        return echartDom.remove();
      }
      console.log(row, "row");
      let sourceTag = row.pointId;
      list = {
        currentsourceId: sourceTag,
        historysourceId: sourceTag,
        // reostartTime:startTime,
        // reoendTime:endTime
      };
      console.log(list, "list");
      $.ajax({
        // url: `/youtian/scene-category/selectSourceTagHistoryListBySourceTag`,
        url: `/youtian/workspace-category/getLineargraph`,
        type: "post",
        dataType: "json",
        data: JSON.stringify(list),
        headers: { "Content-Type": "application/json" },
        success: function (res) {
          console.log(res, "res");
          el.mouseleave(function () {
            $(".tip_text").remove();
          });
          if (res.data.length <= 0) {
            $(".tip_text").remove();
            return el.append(`<div class="tip_text">暂无数据</div>`);
          }
          $("#noneBox").remove();
          el.append(`<div id="noneBox"></div>`);
          let upLimit = el.children("td").eq(3).text();
          let lowLimit = el.children("td").eq(4).text();
          console.log(upLimit, '===========');
          echart(parseInt(upLimit), parseInt(lowLimit), res.data);
        },
      });
    }

    // 封装图表方法
    function echart(upLimit, lowlimit, options) {
      let one = options.splice(0, 30)
      let array = []
      options.forEach(item => {
        console.log(Math.ceil(item.value), '实时----->');
        array.push(Math.ceil(item.value))
      })
      // let optionsSlice = options.slice(10, 20)
      // console.log(optionsSlice, 'optionsSlice');
      // // 图表数据
      // let dataLists = {
      //   data: [],
      //   cjTime: []
      // }
      // optionsSlice.forEach(item => {
      //   dataLists.data.push(item.value)
      //   dataLists.cjTime.push(item.cjTime)
      // })

      // // 页面最大值
      // let dataList = []
      // optionsSlice.forEach(item => {
      //   dataList.push(item.value)
      // });
      // dataList.sort((a, b) => {
      //   return b -a
      // })
      // console.log(dataList, 'dataList');
      var chartDom = document.getElementById("noneBox");
      var myChart = echarts.init(chartDom);
      var option;
      option = {
        tooltip: {
          trigger: "axis",
          boundaryGap: false,
        },
        xAxis: {
          name: "时间",
          type: "category",
          boundaryGap: false,
          data: ["1-1", "1-2", "1-3", "1-4", "1-5"],
        },
        yAxis: {
          name: "数量",
          type: "value",
          min: 0,
          max: 200,
          splitLine: {
            show: false,
          },
        },
        grid: {
          left: "15%",
          right: "20%",
          bottom: "10%",
          top: "20%",
        },
        visualMap: [
          {
            type: "piecewise",
            show: false,
            dimension: 1,
            seriesIndex: 0,
            hoverLink: true,
            pieces: [
              {
                // 不指定 min，表示 min 为无限大（-Infinity）。
                max: lowlimit, // 没有设置最小值，表明当前范围 [-Infinity, max] 变色
                color: "red",
              },
              {
                // 不指定 max，表示 max 为无限大（Infinity）。
                min: upLimit, // 没有设置最大值，表明当前范围 [min, Infinity] 变色
                color: "red",
              },
            ],
            outOfRange: {
              // 在选中范围外 的视觉元素，这里设置在正常范围内的图形颜色
              color: "blue",
            },
          },
        ],
        series: [
          {
            type: "line",
            smooth: true,
            symbol: "none",
            markLine: {
              symbol: "none",
              label: {
                show: true,
              },
              data: [
                {
                  yAxis: lowlimit,
                },
                {
                  yAxis: upLimit,
                },
              ],
            },
            // areaStyle: {},
            // data: [10, 15, 140, 40, 150],
            data: array
          },
        ],
      };
      option && myChart.setOption(option);
      setTimeData = setInterval(() => {
        $.ajax({
          url: `/youtian/workspace-category/getLineargraph`,
          type: "post",
          dataType: "json",
          data: JSON.stringify(list),
          headers: { "Content-Type": "application/json" },
          success: function (res) {
            console.log(res, "length2");
            let now = [];
            let list2 = res.data.splice(0, 30);
            list2.forEach(item => {
              now.push(Math.ceil(item.value))
            })
            if (res.data && res.data.length) {
              option.series[0].data = now;
              option && myChart.setOption(option);
            }
          },
        });
      }, 5000);
    }
    // 渲染左侧树
    // function queryDeptTree() {
    //   var options = {
    //     url: "/youtian/scene-category/ztree",
    //     expandLevel: 2,
    //     onClick: zOnClick,
    //   };
    //   let ab = $.tree.init(options);

    //   function zOnClick(event, treeId, treeNode) {
    //     console.log(event, "event");
    //     console.log(treeId, treeNode, "treeNode");
    //     treeClick = treeNode;
    //     $("#workspaceCategoryId").val(treeNode.id);
    //     $.table.search();
    //   }
    // }

    // 合并行的单元个方法
    jQuery.fn.rowspan = function (colIdx) {
      return this.each(function () {
        var that;
        $("tr", this).each(function (trIndex, trItem) {
          $("td:eq(" + colIdx + ")", this)
            .filter(":visible")
            .each(function (tdIndex, tdItem) {
              if (that != null && $(tdItem).html() == $(that).html()) {
                var rowspan = $(that).attr("rowspan");
                if (rowspan == undefined) {
                  $(that).attr("rowspan", 1);
                  rowspan = $(that).attr("rowspan");
                }
                rowspan = Number(rowspan) + 1;
                $(that).attr("rowspan", rowspan);
                $(tdItem).hide();
              } else {
                that = tdItem;
              }
            });
        });
      });
    };

    $("#btnExpand").click(function () {
      $._tree.expandAll(true);
      $(this).hide();
      $("#btnCollapse").show();
    });

    $("#btnCollapse").click(function () {
      $._tree.expandAll(false);
      $(this).hide();
      $("#btnExpand").show();
    });

    $("#btnRefresh").click(function () {
      queryDeptTree();
    });

    function initAZDWselect1(nextSelectIndex) {
      var params = {
        "jb": 1
      }
      nextSelectIndex = nextSelectIndex ? nextSelectIndex : 1;
      var $nextSelect = $(`#dev_azdw${nextSelectIndex}_select1`);
      if (nextSelectIndex > 1) {
        params = {
          fdwdm: $(`#dev_azdw${nextSelectIndex - 1}_select1`).val()
        }
      }
      $.ajax({
        type: "post",
        url: "/gzmx_scdw/gzmx_scdw/list",
        data: params,
        success: function (res) {
          var optionHTML = `<option value="">请选择</option>`
          for (let i = 0; i < res.length; i++) {
            optionHTML += `<option value="` + res[i].id + `">` + res[i].dwmc + `</option>`
          }
          $nextSelect.html(optionHTML);
        },
        error: function (error) {
          $.modal.alertWarning(error);
        }
      });
    }

    function queryPointSelect1() {
      $("#point-select1").html(`<option value="">请选择</option>`);
      let data = {
        dw_5_id: $("#dev_azdw5_select1").val()
      };
      console.log(data, "data");
      $.ajax({
        method: "POST",
        url: "/gzmx_tag/gzmx_tag/dev_name",
        contentType: "application/json",
        dataType: 'json',
        data: JSON.stringify(data),
        success: function (res) {
          var optionHTML = `<option value="">请选择</option>`;
          for (let i = 0; i < res.data.length; i++) {
            var item = res.data[i];
            optionHTML += `<option value="${item.id}"  >${item.dev_name}</option>`
          }
          $("#point-select1").html(optionHTML);
          $("#upperLimit").val("")
          $("#lowerLimit").val("")
        }
      });
    }
  </script>
</body>

</html>